package fileProcessing;

import java.util.ArrayList;

import entities.Customer;
import entities.Transaction;


public class CorrelationFinding 
{

	//to store the baskets
	private static ArrayList<Transaction> baskets;
	
	//to take care of the promoted items
	private static ArrayList<Integer> promotedItems;
	
	//read the customer specific data i.e. his baskets, items promoted to that customer
	private static void readCustomerData(Customer c)
	{
		baskets = c.getTransactions();
		promotedItems = new ArrayList<Integer>(c.getSelectedForProducts().keySet());
	}
	
	//finding the support of rules and items
	public static double findCorrelation(Customer c)
	{
		readCustomerData(c);
		
		// Calculate the pairwise correlation
		boolean containsA, containsB;
		double correlation, totalCorrelation = 0;
		
		for(int i = 0; i < promotedItems.size() - 1; i++)
		{
			for(int j = 0; j < promotedItems.size() - 1; j++)
			{
				// we do not calculate the correlation for the diagonal line
				if (i == j) continue;
				
				int A = 0, B = 0, AB = 0;
				
				// count the number of transactions that contain A, B, and (A,B)
				for(int k = 0; k < baskets.size(); k++)
				{
					containsA = false;
					containsB = false;
					
					if(baskets.get(k).getProductSet().contains(promotedItems.get(i)))
					{
						A++;
						containsA = true;
					}
					if(baskets.get(k).getProductSet().contains(promotedItems.get(j)))
					{
						B++;
						containsB = true;
					}
					if( containsA && containsB )
						AB++;
				}
				
				if(A == 0 || B == 0)
					correlation = 0;
				else
					correlation = (double)AB / Math.sqrt( (double)(A*B) );
				
				totalCorrelation += correlation;
			}
		}
		totalCorrelation /= 2;	
		
		return totalCorrelation;
	}
}
